package client

import (
	"fmt"
	"io/fs"
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"

	"github.com/go-git/go-git/v5"
	"k8s.io/client-go/util/homedir"
)

type GitClient struct {
}

func (g GitClient) CloneRepo(url string) ([]string, error) {
	path := homedir.HomeDir() + "/tmp/apps"
	fmt.Println(url)
	_, err := git.PlainClone(path, false, &git.CloneOptions{
		URL:      url,
		Depth:    1,
		Progress: os.Stdout,
	})

	if err != nil {
		fmt.Println(err)
		return nil, err
	}

	apps := make([]string, 10)
	appsCnt := 0
	files, _ := ioutil.ReadDir(path)
	for _, file := range files {
		//fmt.Println(file.Name())
		if file.IsDir() {
			// 进入目录，判断是否有package目录
			appPath := path + "/" + file.Name()
			os.Chdir(appPath)
			if file.Name() == "learn-dependencies" {
				mvnPackage()
			}

			filepath.Walk(appPath, func(path string, info fs.FileInfo, err error) error {
				//fmt.Println(path)
				if info.Name() == "package" {
					apps[appsCnt] = file.Name()
					appsCnt++
				}
				return nil
			})
		}
	}
	res := make([]string, appsCnt)
	index := 0
	for _, val := range apps {
		if val != "" {
			res[index] = val
			index++
		}
	}
	return res, nil
}

func mvnPackage() {
	cmd := exec.Command("mvn", "clean", "package")
	cmderr := cmd.Run()
	if cmderr != nil {
		fmt.Println(cmd.Stdout)
		fmt.Println(cmd.Stderr)
	}
}
